<template>
    <div>
        <!-- 筛选区域 -->
        <div class="filters">
            <el-form label-width="130px" inline>
                <el-form-item label="选择排序">
                    <el-select v-model="selectedScore" placeholder="选择成绩排序" @change="onScoreChange">
                        <el-option v-for="score in scoreFields" :key="score.value" :label="score.label"
                            :value="score.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择录取状态">
                    <el-select v-model="selectedStatus" placeholder="选择录取状态" @change="onStatusChange">
                        <el-option v-for="status in statusOptions" :key="status.value" :label="status.label"
                            :value="status.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择录取志愿方向">
                    <el-select v-model="selectedDirection" placeholder="选择录取志愿方向" @change="onDirectionChange">
                        <el-option v-for="direction in directions" :key="direction.value" :label="direction.majorName"
                            :value="direction.majorName" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择录取结果">
                    <el-tooltip effect="dark" :disabled="!resultDisabled" content="录取状态是未录取时，不可选择录取结果" placement="top">
                        <el-select v-model="selectedResult" placeholder="选择录取结果" @change="onResultChange"
                            :disabled="resultDisabled">
                            <el-option v-for="direction in directions" :key="direction.value"
                                :label="direction.majorName" :value="direction.majorName" />
                        </el-select>
                    </el-tooltip>
                </el-form-item>
                <!-- 重置按钮 -->
                <el-button type="warning" @click="resetFoem">
                    重置条件
                </el-button>
                <el-tooltip effect="dark" content="请勾选学生信息" placement="top">
                    <el-button type="primary" @click="batchAddAdmission" :disabled="!batchAddAdmissionShow">
                        批量添加录取
                    </el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="未勾选数据则全部导出" placement="top">
                    <el-button type="success" @click="showExportDialog">
                        导出为 Excel
                    </el-button>
                </el-tooltip>

                </el-form-item>
            </el-form>
        </div>

        <!-- 数据表格 -->
        <el-table :data="filteredStudents" ref="studentTable" @selection-change="handleSelectionChange" border
            style="width: 100%">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="name" label="姓名" width="80" align="center" />
            <el-table-column prop="studentId" label="学号" align="center" />
            <el-table-column prop="className" label="班级" align="center" />
            <el-table-column prop="webScore" label="网页设计与制作" align="center" />
            <el-table-column prop="javaScore" label="面向对象程序设计（Java）" width="120" align="center" />
            <el-table-column prop="programScore" label="程序设计基础" align="center" />
            <el-table-column prop="databaseScore" label="数据库应用技术" align="center" />
            <el-table-column prop="webTotal" label="以web成绩为主" align="center" />
                <el-table-column prop="javaTotal" label="以java成绩为主" align="center" />
                <el-table-column prop="programTotal" label="以program成绩为主" align="center" />
                <el-table-column prop="databaseTotal" label="以database成绩为主" align="center" />
            <el-table-column prop="applicationOne" label="志愿填报一" align="center" />
            <el-table-column prop="applicationTwo" label="志愿填报二" align="center" />
            <el-table-column prop="result" label="录取结果" align="center">
                <template slot-scope="scope">
                    <template v-if="editingRow === scope.row.studentId">
                        <!-- 编辑状态：显示下拉框 -->
                        <el-select v-model="filteredStudentsResult" placeholder="选择录取志愿方向" size="small"
                            style="width: 100%;">
                            <el-option v-for="direction in directions" :key="direction.value"
                                :label="direction.majorName" :value="direction.majorName" />
                        </el-select>
                    </template>
                    <template v-else>
                        <!-- 非编辑状态：显示文本 -->
                        {{ scope.row.result || '未录取' }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="录取状态" align="center">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">
                        {{ scope.row.status == 1 ? '已录取' : '未录取' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <template v-if="editingRow === scope.row.studentId">
                        <el-button type="success" v-if="scope.row.status == 1" size="small"
                            @click="finishEdit(scope.row)">完成修改</el-button>
                        <el-button type="success" v-else size="small" @click="addAdmission(scope.row)">完成添加</el-button>
                    </template>
                    <template v-else>
                        <el-button style="color: #f56c6c;" type="text" size="small"
                            @click="delStudent(scope.row.id)">删除学生</el-button>
                        <el-button v-if="scope.row.status == 0" type="text" size="small"
                            @click="startEdit(scope.row)">添加录取</el-button>
                        <el-button v-else type="text" size="small" @click="startEdit(scope.row)">修改录取</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="totalStudents" />

        <!-- 导出对话框 -->
        <el-dialog title="导出数据" :visible.sync="exportDialogVisible" width="80%">
            <el-table :data="selectedStudents" border style="width: 100%;max-height: 650px;overflow-y: auto;">
                <!-- <el-table-column type="selection" width="55" align="center" /> -->
                <el-table-column prop="name" label="姓名" width="80" align="center" />
                <el-table-column prop="studentId" label="学号" align="center" />
                <el-table-column prop="className" label="班级" align="center" />
                <el-table-column prop="webScore" label="网页设计与制作" align="center" />
                <el-table-column prop="javaScore" label="面向对象程序设计（Java）" align="center" />
                <el-table-column prop="programScore" label="程序设计基础" align="center" />
                <el-table-column prop="databaseScore" label="数据库应用技术" align="center" />
                <el-table-column prop="webTotal" label="以web成绩为主" align="center" />
                <el-table-column prop="javaTotal" label="以java成绩为主" align="center" />
                <el-table-column prop="programTotal" label="以program成绩为主" align="center" />
                <el-table-column prop="databaseTotal" label="以database成绩为主" align="center" />
                <el-table-column prop="applicationOne" label="志愿填报一" align="center" />
                <el-table-column prop="applicationTwo" label="志愿填报二" align="center" />
                <el-table-column prop="result" label="录取志愿" align="center" />
                <el-table-column prop="status" label="录取状态" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                            {{ scope.row.status === 1 ? '已录取' : '未录取' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="danger" size="small" @click="removeStudent(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="exportDialogVisible = false">取消</el-button>
                <el-button type="success" @click="confirmExport">确认导出</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "admission",
        data() {
            return {
                selectedScore: null,
                selectedStatus: null,
                selectedDirection: null,
                selectedResult: null,
                // 按钮状态
                batchAddAdmissionShow: false,
                // 成绩排序字段
                scoreFields: [
                    // { label: "网页设计与制作", value: "web_score" },
                    // { label: "面向对象程序设计（Java）", value: "java_score" },
                    // { label: "程序设计基础", value: "program_score" },
                    // { label: "数据库应用技术", value: "database_score" },
                    { label: "以web成绩为主", value: "web_total" },
                    { label: "以java成绩为主", value: "java_total" },
                    { label: "以program成绩为主", value: "program_total" },
                    { label: "以database成绩为主", value: "database_total" },
                ],
                // 录取状态选项
                statusOptions: [
                    { label: "已录取", value: "1" },
                    { label: "未录取", value: "0" },
                ],
                // 录取志愿方向选项
                directions: [
                    // { label: "方向1", value: "direction1" },
                    // { label: "方向2", value: "direction2" },
                ],
                directionsOptions: '',
                // 控制录取结果下拉框的禁用状态
                resultDisabled: false,
                selectedStudents: [], // 当前选中的学生
                students: [], // 学生数据
                filteredStudents: [],
                currentPage: 1,
                pageSize: 10,
                totalStudents: 0,
                exportDialogVisible: false, // 控制导出对话框的显示
                editingRow: null, // 当前正在编辑的行
                filteredStudentsResult: '',
            };
        },
        methods: {
            // 获取学生数据
            getData(score, status, direction, result) {
                this.$get('/api/studentInfo', { total: score, status: status, majorFilter: direction, result: result }).then(res => {
                    this.students = res.data;
                    this.totalStudents = res.data.length; // 更新总学生数
                    this.filteredStudents = res.data.slice(0, this.pageSize); // 初始化分页数据
                    // 定位到当前页
                    this.handleCurrentChange(this.currentPage);
                    // this.updatePagination();

                });
            },
            handleSelectionChange(val) {
                this.selectedStudents = val; // 更新选中的学生
                console.log(this.batchAddAdmissionShow);

                // 检查选中学生的状态
                this.batchAddAdmissionShow = this.selectedStudents.some(student => student.status === 0) && this.selectedStudents.length > 0;
                this.batchAddAdmissionShow = !this.selectedStudents.some(student => student.status === 1) && this.selectedStudents.length > 0;

            },
            // 添加录取
            addAdmission(student) {
                this.editingRow = null;
                this.$post('/api/studentInfo/admit',
                    { studentIds: [student.studentId], admittedMajor: this.filteredStudentsResult })
                    .then(res => {
                        if (res.code == 200) {
                            this.$message.success('添加录取成功');
                        } else {
                            this.$message.error(res.msg);
                        }
                        // console.log(res.data);
                        this.getData(this.selectedScore, this.selectedStatus, this.selectedDirection, this.selectedResult);; // 重新获取数据以更新表格
                    })
            },
            // 批量添加录取
            batchAddAdmission() {
                if (this.selectedDirection == null) {
                    // console.log("请选择录取志愿方向");
                    this.$message.error("请选择录取志愿方向");
                    return;
                }
                let studentIds = [];
                this.selectedStudents.forEach(student => {
                    studentIds.push(student.studentId)
                })

                this.$post('/api/studentInfo/admit',
                    { studentIds: studentIds, admittedMajor: this.selectedDirection })
                    .then(res => {
                        if (res.code == 200) {
                            this.$message.success('批量添加录取成功');
                        } else {
                            this.$message.error(res.msg);
                        }
                        // console.log(res.data);
                        this.getData(this.selectedScore, this.selectedStatus, this.selectedDirection, this.selectedResult); // 重新获取数据以更新表格
                    })
            },
            showExportDialog() {
                // 如果没有选中学生，则导出所有学生
                if (this.selectedStudents.length === 0) {
                    this.selectedStudents = this.students; // 将所有学生数据赋值给选中学生
                }
                this.exportDialogVisible = true; // 显示导出对话框
            },
            // 重置表单
            resetFoem() {
                console.log("重置表单");
                this.selectedScore = null,
                    this.selectedStatus = null,
                    this.selectedDirection = null,
                    this.selectedResult = null
                this.getData(this.selectedScore, this.selectedStatus, this.selectedDirection, this.selectedResult);
            },
            confirmExport() {
                // console.log("确认导出以下数据：", this.selectedStudents);
                this.exportDialogVisible = false; // 关闭对话框
                this.$downs('/api/studentInfo/export', this.selectedStudents).then(res => {
                    // if (res.code == 200) {
                    this.$message({
                        message: "导出成功",
                        type: "success",
                    });
                    // } else {
                    //     this.$message.error(res.msg);
                    // }
                });
                this.selectedStudents = []; // 清空选中的学生
                // 取消选中状态
                this.$refs.studentTable.clearSelection();
            },
            // 删除学生
            delStudent(id) {
                // console.log("删除学生，ID:", id);

                this.$confirm('此操作将永久删除该学生, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    this.$delete(`/api/studentInfo/${id}`).then(res => {
                        // console.log(res);
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getData(this.selectedScore, this.selectedStatus, this.selectedDirection, this.selectedResult); // 重新获取数据以更新表格
                    })
                    // 在这里添加删除学生的逻辑，例如调用 API 删除学生数据
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            // 移除弹窗中的学生
            removeStudent(student) {
                // 从 selectedStudents 中移除指定学生
                this.selectedStudents = this.selectedStudents.filter(s => s.studentId !== student.studentId);
            },
            handleSizeChange(size) {
                this.pageSize = size;
                this.updatePagination();
            },
            handleCurrentChange(page) {
                this.currentPage = page;
                this.updatePagination();
            },
            updatePagination() {
                const start = (this.currentPage - 1) * this.pageSize;
                const end = start + this.pageSize;
                this.filteredStudents = this.students.slice(start, end);
            },
            onScoreChange(value) {
                // console.log("选择成绩排序发生变化：", value);
                this.getData(this.selectedScore, this.selectedStatus, this.selectedDirection, this.selectedResult);
            },
            onStatusChange(value) {

                if (value == 1) {
                    this.resultDisabled = false; // 禁用下拉框
                } else {
                    this.resultDisabled = true; // 禁用下拉框
                }
                this.getData(this.selectedScore, this.selectedStatus, this.selectedDirection, this.selectedResult);
            },
            onDirectionChange(value) {
                // console.log("选择录取志愿方向发生变化：", value);
                this.getData(this.selectedScore, this.selectedStatus, this.selectedDirection, this.selectedResult);
            },
            onResultChange() {
                // console.log(this.selectedScore, this.selectedStatus, this.selectedDirection, this.selectedResult);

                this.getData(this.selectedScore, this.selectedStatus, this.selectedDirection, this.selectedResult);
            },
            startEdit(row) {
                this.editingRow = row.studentId;
                this.filteredStudentsResult = row.result; // 将当前行的结果赋值给下拉框
            },
            finishEdit(row) {
                this.editingRow = null;
                if (this.filteredStudentsResult == undefined || this.filteredStudentsResult == '') {
                    this.$message.error('请选择录取结果');
                    // ('请选择录取结果');
                    return;
                }
                this.$put('/api/studentInfo/', { id: row.id, result: this.filteredStudentsResult }).then(res => {
                    // console.log(res.data);
                    if (res.code == 200) {
                        this.$message.success('修改成功');
                        this.getData(this.selectedScore, this.selectedStatus, this.selectedDirection, this.selectedResult); // 重新获取数据以更新表格
                    }
                })
            },
        },
        created() {
            // 获取列表数据
            this.getData();
            // 获取课程详情数据
            // this.$get().then(res=>{
            //     console.log(res.data);
            // })
            // 获取专业详情数据
            this.$get('/api/majorDetails').then(res => {
                console.log(res.data);
                // this.scoreFields = res.data
                this.directions = res.data
            });
        }
    };
</script>

<style scoped>
    .filters {
        margin-bottom: 20px;
        display: flex;
        gap: 10px;
    }

    .el-button.is-disabled {
        color: #c1c1c1;
        background-color: #f5f7fa;
        border-color: #dcdfe6;
    }
</style>